<template>
  <div class="col">
    <div class="row g-3 align-items-center mb-3">
      <div class="col-auto">
        <label class="col-form-label" :style="labelStyle">
          <slot></slot>
        </label>
      </div>
      <div class="col">
        <textarea v-if="type=='textarea'"
                  class="lay-form form-control"
                  v-model="inputRef.value"
                  @blur="validate"
                  :rows="row"
                  ref="formInput"
                  v-bind="$attrs" />

        <input v-else-if="type=='password'"
               type="password"
               class="lay-form form-control"
               v-model="inputRef.value"
               @blur="validate"
               :rows="row"
               ref="formInput"
               v-bind="$attrs" />

        <input v-else
               class="lay-form form-control"
               v-model="inputRef.value"
               @blur="validate"
               ref="formInput"
               v-bind="$attrs" />
        <div style="height:20px;position:absolute">
          <div class="invalid-feedback"
               style="display:block;font-size:10px;margin-top:0">{{inputRef.message}}</div>
        </div>

      </div>
    </div>
  </div>

</template>

<script lang='ts'>
import { defineComponent, PropType, watch, onMounted } from 'vue'
import inputValidator, { RulesProp, InputRef } from '@/hooks/inputValidator'
import config from '@/static/config/uisetting.ts'
import '@/static/css/common.css'

export default defineComponent({
  name: 'ChuText',
  props: {
    rules: {
      type: Array as PropType<RulesProp>,
      default: []
    },
    modelValue: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'text'
    },
    row: {
      type: [String, Number],
      default: 3
    },
    required: Boolean,
    formId: String
  },
  // 不让根元素继承父组件的属性
  inheritAttrs: false,
  setup (props, context) {
    // 校验器--start
    const rules = props.rules.slice()
    if (props.required) {
      rules.push('required')
    }
    const refs: InputRef = {
      error: false,
      value: props.modelValue,
      message: ''
    }
    const { inputRef, validate } = inputValidator(rules, refs)
    watch(inputRef, () => {
      context.emit('update:modelValue', inputRef.value)
    })
    // 校验器--end

    // 页面样式控制--start
    const labelStyle = {
      width: config.formLabelMaxWidth,
      fontSize: config.labelSize,
      textAlign: 'right'
    }
    // 页面样式控制--end

    const formCheckData: FormCheckData = {
      validate: validate,
      formId: props.formId
    }
    onMounted(() => {
      chu.listener.emit('form-item-created', formCheckData)
    })

    return {
      inputRef,
      validate,
      labelStyle
    }
  }
})
</script>

<style>
</style>
